// bstation
console.log('bstation :-)');

bstation={
	
	loadScript:function(url,cb){
		if(Array.isArray(url)){			
			url.map(function(u){bstation.loadScript(u)});
		}
		else{
				var s = document.createElement('script');
				s.src = url;
				s.onload=cb;
				document.head.appendChild(s);	
		}
	},

	uid:function(prefix){
		if(!prefix){prefix='UID'}
		var uid=prefix+Math.random().toString().slice(2);
		return uid
	},
	
	loadLink:function(url){
		var lk = document.createElement('link');
		lk.rel="stylesheet";
		lk.href=url;
		lk.type="text/css";
		lk.media="all";
		document.head.appendChild(lk);
	},
	
	runWhen:function(fun,vars){
		// have fun only after variable is there
		if(typeof(vars)=="string"){vars=[vars]}; // making sure it is an array
		if(typeof(window[vars[0]])=="undefined"){ // if not found
			console.log(vars[0]+' not found');
			if(vars.length>0){setTimeout(function(){bstation.runWhen(fun,vars)},1000)} // wait a second and try again
		}
		else{
			console.log(vars[0]+' found');
			if(vars.length>0){bstation.runWhen(fun,vars.slice(1))} // keep going
			else{fun()} // have fun
		}
		
	},
	/*
	start:function(id){ // starts bstation in div with id
		// load libraries
		this.loadLink('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/smoothness/jquery-ui.css');
		this.loadScript([
			"https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
			"https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js",
			"https://www.google.com/jsapi"
		]);
		// wait for jQuery before proceeding
		var wait = 0
		if(typeof(id)=='undefined'){wait = 3000 };
		//set
		
		
		// populate div
		//console.log(jQuery);
		
	},
	*/

    UI:function(id){ // assembles ui at element id (or with that id)
		if(typeof(id)=='string'){div0=document.getElementById(id)}else{div0=id}
		div0.innerHTML='<p>Connect to database:</p>';
		jQuery(div0).addClass('container');         
		// load postmongo
		//jQuery.getScript('https://raw.github.com/ibl/postmongo/master/postmongo.js');
		jQuery.getScript('https://postmongo.googlecode.com/git/postmongo.js');
		//jQuery.getScript('http://localhost:8888/postmongoGit/postmongo.js');


		uid=bstation.uid('mongodb_');
		// Preparing for Login UI
		bstation.UI.remember=function(that,uid){
			// Make sure there is a default value in memory
			if(that.checked&(jQuery('#db_'+uid).val().length==0)){ // if there is nothing in the address box, get from localStorage
				if(!localStorage.bstationDBparm){ // if there isn't anything in localStorage use demo 
					localStorage.bstationDBparm=JSON.stringify({
						db:'ds035348.mongolab.com:35348/board',
						u:'demo',
						p:'demo'});
				}
			}
			// now that we're sure to have something in localStorage lets try again
			var parm = JSON.parse(localStorage.bstationDBparm);

			if(that.checked){
				if(jQuery('#db_'+uid).val().length==0){jQuery('#db_'+uid).val(parm.db||"")}
				if(jQuery('#username_'+uid).val().length==0){jQuery('#username_'+uid).val(parm.u||"")}
				if(jQuery('#password_'+uid).val().length==0){jQuery('#password_'+uid).val(parm.p||"")}
			}

		};

		bstation.UI.connect=function(that,uid){
			//console.log('connect to ', that, 'with  uid '+uid);
			console.log(uid);
			// collect parameters from inputs
			var p = {}
			p.db=jQuery('#db_'+uid).val();
			p.u=jQuery('#username_'+uid).val();
			p.p=jQuery('#password_'+uid).val();
			p.server='https://postmongo.herokuapp.com';
			bstation[uid]= new postmongo(p,function(){

			});


		};

		jQuery('<div id="div_'+uid+'" style="color:navy"><form class="form-inline">mongo <input id="db_'+uid+'" type="text" size="200" class="input-large search-query" placeholder="database address" size="100"> -u <input id="username_'+uid+'" type="text" class="input-small" placeholder="username"> - p <input id="password_'+uid+'" type="password" class="input-small" placeholder="Password"></form><button id="connect_'+uid+'" class="btn" onclick="bstation.UI.connect(this,uid);">Connect</button> <input id="remember_'+uid+'" type="checkbox" onclick="bstation.UI.remember(this,uid);"> Remember </div>').appendTo(div0);
			//jQuery('#remember_'+uid).attr('onclick',function(){alert('I remember')});
	},

	createAlert:function(msg,target,uid){
		jQuery('<div id="'+uid+'" class="alert">'+msg+'</div>').appendTo(target);
	},


	loadTCGApatients:function(i){
		bstation.loadTCGApatients.docs=[];
		// list of patient tables (list borrowed from David's SPARQL endpoint)
		if(!window.pp){
			var pp=["https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/gbm/bcr/biotab/clin/clinical_patient_gbm.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/ov/bcr/biotab/clin/clinical_patient_ov.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/coad/bcr/biotab/clin/clinical_patient_coad.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lusc/bcr/biotab/clin/clinical_patient_lusc.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/luad/bcr/biotab/clin/clinical_patient_luad.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/kirp/bcr/biotab/clin/clinical_patient_kirp.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/ucec/bcr/biotab/clin/clinical_patient_ucec.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/read/bcr/biotab/clin/clinical_patient_read.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lihc/bcr/biotab/clin/clinical_patient_lihc.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/skcm/bcr/biotab/clin/clinical_patient_skcm.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/cesc/bcr/biotab/clin/clinical_patient_cesc.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/laml/bcr/biotab/clin/clinical_patient_laml.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/prad/bcr/biotab/clin/clinical_patient_prad.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/hnsc/bcr/biotab/clin/clinical_patient_hnsc.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/thca/bcr/biotab/clin/clinical_patient_thca.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/blca/bcr/biotab/clin/clinical_patient_blca.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/kirc/bcr/biotab/clin/clinical_patient_kirc.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/stad/bcr/biotab/clin/clinical_patient_stad.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/lgg/bcr/biotab/clin/clinical_patient_lgg.txt", "https://tcga-data.nci.nih.gov/tcgafiles/ftp_auth/distro_ftpusers/anonymous/tumor/brca/bcr/biotab/clin/clinical_patient_brca.txt"];
		}
		// make sure jmat is loaded already
		if(!window.jmat){this.loadScript('http://localhost:8888/jmat/jmat.js',function(){
			// note different urlread service, more at https://script.google.com/a/mathbiol.org/d/1X-Ay-hwObDMqyz50ffUTkM_QSwb_JGz7eE6y1VQU9TDi6reGi7l2UpFQ/edit
			jmat.webrwUrl="https://script.google.com/macros/s/AKfycbzyVWTAXybGiTfiZXv3cy5CFO8b9Wn4noStMdSYFSCBNvVG2pME/exec";
			bstation.loadTCGApatients();
		})}
		// https://jmat.googlecode.com/git/jmat.js
		else{
			// read one at a time
			//var i = 0;
			function loadTable(i){
				jmat.urlread_text2doc(pp[i],function(x){
					console.log('#'+i+':'+x.length);
					// bstation.loadTCGApatients.docs[i]={url:pp[i],dt:x};
					bstation.loadTCGApatients.docs[i]=x;
					delete x;
					if(i<(pp.length-1)){loadTable(i+1)}
				})
			}
			loadTable(0);
		}
		return bstation.loadTCGApatients.docs;

		//Example of loading all patients into a mongodb repository
		//t = setInterval(function(){i++;db2.patient.save(bstation.loadTCGApatients.docs[i],function(){console.log('#'+i+' done');if(i==19){clearInterval(t)}})},10000)


	}
}